package cn.tedu.sp06.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    //设置过滤器的类型，pre、routing、post、error
    @Override
    public String filterType() {
        String preType = FilterConstants.PRE_TYPE;
        return preType;
    }

    //位置序号
    @Override
    public int filterOrder() {
        return 6;
    }

    //针对当前请求是否执行过滤代码
    @Override
    public boolean shouldFilter() {

        /**
         * 调用商品判断权限
         * 调用用户和订单，不检查权限
         */

        //获得调用的服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equals(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {

        //根据token
        // 获得request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 接受token参数
        String token = request.getParameter("token");
        // 如果没有token，阻止访问，返回响应
        if (StringUtils.isBlank(token)) {

            // 阻止访问
            currentContext.setSendZuulResponse(false);
            // 直接返回响应
            currentContext.addZuulResponseHeader("Content-Type","text/html;charset=utf-8");
            currentContext.setResponseBody("not token !");

        }

        return null;
    }

}
